package com.istock.union.security;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import com.istock.base.serializer.JsonSerializer;
import com.istock.base.serializer.json.JsonSerializerFactory;
import com.istock.base.web.filter.XssSqlFilter;
import com.istock.union.user.client.SSOClientUtils;
import com.istock.union.user.model.SecurityChecker;
import com.istock.union.user.utils.WebCommonUtils;

/**
 * @author 权限标签认证
 * 权限的认证在controller里面,controller已经是在业务层面
 * 通过@SecurityChecker的注解,拦截所有的注解方法,验证注解内的权限标识
 * 如果没有权限,不能调用controller方法,直接返回
 * 本权限验证,如果不通过,只返回403
 */
@Aspect
public class SecurityCheckerAspect {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private String forbiddenUrl = "";
	
	@Around(value="within(@org.springframework.stereotype.Controller *) && @annotation(SecurityChecker)",argNames="SecurityChecker")
	public Object check(ProceedingJoinPoint pjp , SecurityChecker checkAnnotation) throws Throwable {
		
		String permissStr = checkAnnotation.value();
		logger.info("================the annotation str :{}=========" , permissStr);
		if(hasPermission(permissStr)) {
			//如果配置的权限标识在用户的赋权标识里面
			return pjp.proceed();
		}else {
			//向response里面写入403
			logger.info("the permissStr:{} , current can't has the permiss" , permissStr);
			
//			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//			HttpServletResponse response = ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();
			HttpServletRequest request = XssSqlFilter.findRequest();
			HttpServletResponse response = XssSqlFilter.findResponse();
			
			writeResponse(request , response);
		}
		return null;
	}
	
	public void writeResponse(HttpServletRequest request , HttpServletResponse response) throws Exception {
		boolean isAjax = WebCommonUtils.isAjax(request);
		if(isAjax){
			//如果是ajax,返回403,由前端负责跳转到登录页面
			response.setStatus(HttpStatus.FORBIDDEN.value());
			Map<String , Object> resultMap = new HashMap<String, Object>();
			resultMap.put("forbiddenUrl", WebCommonUtils.generateTargetUrl(request.getContextPath(), forbiddenUrl));
//			response.setContentType(MediaType.APPLICATION_JSON_VALUE);
			
			response.setContentType("application/json");
			JsonSerializer serializer = JsonSerializerFactory.findSerializer();
			response.getWriter().println(serializer.serialize(resultMap));
//			response.getWriter().println(JSON.toJSONString(resultMap));
			response.getWriter().flush();
			return;
		}
		
		response.sendRedirect(WebCommonUtils.generateTargetUrl(request.getContextPath(), forbiddenUrl));
	}
	
	public static boolean isAjax(HttpServletRequest request){
		return (request.getHeader("X-Requested-With") != null  && "XMLHttpRequest".equals( request.getHeader("X-Requested-With"))) ;
	}
	
	private boolean hasPermission(String permiss) {
		return SSOClientUtils.getInstance().hasPermiss(permiss);
	}
}
